var grid = null;//表格对象
var treeManger; //树对象
var data;
var userManger;


var $modal = $('#ajax-modal');
var $smallModal = $("#smallModal");
var btnAddNew = $("#btnAddNew");
var btnUpdate = $("#btnUpdate");
var btnStart = $("#btnStart");
var btnStop = $("#btnStop");
var btnRePwd = $("#btnRePwd");
var btnDel = $("#btnDel");

/*
 * 初始化加载
 */
$(function () {

    btnAddNew.click(function (e) {
        addNew();
    });
    btnUpdate.click(function (e) {
        updUserInit();
    });
    btnStart.click(function (e) {
        updUserStatus("01");
    });
    btnStop.click(function (e) {
        updUserStatus("02");
    });
    btnRePwd.click(function (e) {
        resetPassword();
    });
    btnDel.click(function (e) {
        delUser();
    });

    $modal.on('hidden.bs.modal', function (e) {
        removeDetail();
    })

    //查询用户信息列表
    var url = _path + "/user/list";
    findUserInfoList(url);
    $("#Submitbutton").bind("click", function () {
        var organName = $("#organName").val();
        var userName = $("#userName").val();
        var userRealName = $("#userRealName").val();
        var url = "/user/findUserInfoListAjax?userRealName=" + userRealName + "&userName=" + userName + "&organName=" + organName;
        findUserInfoList(url);
    });
});

function getWhere(attrs) {
    if (!grid || !attrs) return null;
    var clause = function (rowdata, rowindex) {
        for (var i = 0, len = attrs.length; i < len; i++) {
            if ((rowdata[attrs[i]].toLowerCase().indexOf($("#" + attrs[i]).val().toLowerCase()) == -1)) {
                return false;
            }
        }
        return true;
    };
    return clause;
}

/*
 * 查询用户信息列表数据
 */
function findUserInfoList(url) {
    $.ajax({
        url: url,
        type: "POST",
        async: false,
        dataType: "json",
        success: function (result) {
            data = result;
            var pageSize = 20;
            grid = $("#maingrid").ligerGrid({
                width: '98%',
                height: '98%',
                headerRowHeight: 36,
                rowHeight: 36,
                checkbox: true,
                columns: [
                    { display: 'ID', name: 'id', width: '0%', align: 'left', hide: true},
                    { display: '用户名', name: 'username', width: '15%' },
                    { display: '真实姓名', name: 'realname', width: '15%' },
                    { display: '所属机构', name: 'organ.organame', width: '20%' },
                    { display: '联系电话', name: 'tel', width: '15%' },
                    { display: 'E-Mail', name: 'email', width: '15%' },
                    { display: '用户状态', name: 'status', width: '15%', type: 'int', align: 'center', render: function (row) {
                        if (row.status == "01") {
                            return "<i class='fa fa-check'></i>";
                        } else if (row.status == "02") {
                            return "<i class='fa fa-frown-o'></i>";
                        } else if (row.status == "04") {
                            return "<i class='fa fa-unlock-alt'></i>";
                        }


                    }}
                ], where: getWhere(), data: data, pageSize: 20, rownumbers: true, pageParmName: "curNo", pagesizeParmName: "curSize"
            });
            $("#pageloading").hide();
        }
    });
}

/*
 * 查询用户信息
 */
/*function doSearch(){
 var userNo = $("#userNo").val() ;
 var userName = $("#userName").val() ;
 var url="/user/findUserInfoListAjax?userNo="+userNo+"&userName="+userName ;
 findUserInfoList(url);
 }*/

function save() {
    //if(validation()){ // 校验提交
    App.ajax(_path + "/user/addUser", $("#formDetail").serialize(), saveResult);
//	}
}
function saveResult(data) {
    if (data == '200') {
        App.bubble(200, "保存成功！");
        $modal.modal('hide');
        //	window.location.reload();
        findUserInfoList(_path + "/user/list");
        //grid.reload(); //重新加载不查询数据库
    } else if (data == '500') {
        App.bubble(500, "保存失败！");
    } else if (data == '409') {
        App.bubble(500, "该用户已存在！");
    }
}

/*
 * 新增用户信息初始化
 */
function addNew() {
    initOgrTree();
    passRole();
    $modal.modal('show');
}

/*
 * 修改用户信息初始化
 */
function updUserInit() {
    //获取选中记录行
    var rowid = grid.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择需要修改的用户！");
        return false;
    }
    if (length == 1) {
        App.ajax(_path + "/user/updUserInit", "userId=" + rowid[0].id, function (data) {
            $("#id").val(data.id);
            $("#username").val(data.username);
            $("#organid").val(data.organid);
            $("#organname").val(data.organame);
            $("#realname").val(data.realname);
            $("#tel").val(data.tel);
            $("#email").val(data.email);
            initOgrTree();
            passRole();
        });
        $modal.modal('show');
    } else {
        App.bubble(500, "只能选择一个用户信息进行修改！");
    }
}

function passRole() {
    App.ajax(_path + "/role/initRole", "", function (data) {
        var array = data.roleList;
        var roleData = [];
        for (var k = 0; k < array.length; k++) {
            roleData.push({
                'id': array[k].id,
                'text': array[k].rolename
            });
        }
        App.ajax(_path + "/user/findUserRole", "userId=" + $("#id").val(),
            function (data) {
                var userRoledata = data.list;
                var roles = [];
                for (var i = 0; i < userRoledata.length; i++) {
                    roles.push(userRoledata[i]);
                }
                $(".select2_sample3").select2({
                    multiple: true,
                    data: roleData
                });
                $(".select2_sample3").select2("val", roles);
            });
    });
}
function removeDetail(data) {
    $(':input', '#formDetail')
        .not(':button, :submit, :reset')
        .val('').removeAttr('checked').removeAttr('selected');
    //$(".select2_sample3").select2("val", '');
}

/*
 *删除选中的用户信息 
 */
function delUser() {
    //用self参数来标识要删除的用户是否是登录账号本身
    var self = false;
    var userId = '';
    //获取选中记录行
    var rowid = grid.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择要删除的记录！");
        return false;
    } else if (length > 0) {
        //判断选择的记录中是否含有登录账号本身
        for (var i = 0; i < length; i++) {
            if (rowid[i].id == "${userId}") {
                self = true;
            }
        }
        if (self == true) {
            App.bubble(500, "所选记录中包含当前登录账号，不允许进行删除操作！");
            return;
        } else if (confirm('确实要删除选择的' + rowid.length + '条记录吗')) {
            for (var i = 0; i < length; i++) {//获取删除的ID
                if (i < length - 1) {
                    userId += rowid[i].id + ",";
                } else {
                    userId += rowid[i].id;
                }
            }
            $.ajax({
                type: "post",
                url: _path + "/user/delUser",
                data: {
                    "userIds": userId
                },
                success: function (data) {
                    //如果删除成功，则刷新页面！
                    if (data["message"] == "1") {
                        App.bubble(200, "删除用户成功！");
                    } else if (data["message"] == "0") {
                        App.bubble(500, "删除用户失败！");
                    } else {
                        App.bubble(500, data["message"]);
                    }
                    //删除用户信息后查询初始化
                    findUserInfoList(_path + "/user/list");
                },
                error: function () {
                    App.bubble(500, "删除用户失败！");
                }
            });

        }
    }
}

/*
 *密码重置 
 * */
function resetPassword() {
    //获取选中记录行
    var rows = grid.getSelecteds();
    var userId = '';
    if (rows.length == 0) {
        App.bubble(500, "请选择用户！");
    } else {
        for (var i in rows) {
            userId += rows[i].id + ",";
        }
        $.ajax({
            type: "post",
            url: _path + "/user/resetPassword",
            data: {
                "userIds": userId
            },
            success: function (data) {
                //如果删除成功，则刷新页面！
                if (data["message"] == "1") {
                    App.bubble(200, "密码重置666666成功！");
                } else if (data["message"] == "0") {
                    App.bubble(500, "密码重置失败！");
                } else {
                    App.bubble(500, data["message"]);
                }
            },
            error: function () {
                App.bubble(500, "密码重置失败！");
            }
        });

    }
}

/*
 * 用户信息	启用和停用操作
 */
function updUserStatus(status) {
    //用self参数来标识要操作的用户是否是登录账号本身
    var self = false;
    var userId = '';
    var curStatusCode = '';
    //获取选中记录行
    var rowid = grid.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择要启用或停用的用户记录！");
        return false;
    } else if (length > 0) {
        for (var i = 0; i < length; i++) {
            curStatusCode = rowid[i].status;
            if (curStatusCode == "02" && status == "02") {
                App.bubble(500, "选择记录中存在【禁用】状态的用户！");
                return false;
            } else if (curStatusCode == "01" && status == "01") {
                App.bubble(500, "选择记录中存在【正常】状态的用户！");
                return false;
            }
        }
        //判断选择的记录中是否含有登录账号本身
        for (var i = 0; i < length; i++) {
            if (rowid[i].id == "${userId}") {
                self = true;
            }
        }
        if (self == true) {
            App.bubble(500, "所选记录中包含当前登录账号，不允许进行启用和停用操作！");
            return;
        } else if (confirm('确定要启用、停用选择的' + rowid.length + '条记录吗')) {
            //获取需要操作的用户ID
            for (var i = 0; i < length; i++) {
                if (i < length - 1) {
                    userId += rowid[i].id + ",";
                } else {
                    userId += rowid[i].id;
                }
            }
            $.ajax({
                type: "post",
                url: _path + "/user/updUserStatus",
                data: {
                    "userIds": userId,
                    "status": status
                },
                success: function (data) {
                    //如果删除成功，则刷新页面！
                    if (data["message"] == "1" && status == "01") {
                        App.bubble(200, "用户启用成功！");
                    } else if (data["message"] == "0" && status == "01") {
                        App.bubble(500, "用户启用失败！");
                    } else if (data["message"] == "1" && status == "02") {
                        App.bubble(200, "用户停用成功！");
                    } else if (data["message"] == "0" && status == "02") {
                        App.bubble(500, "用户停用失败！");
                    } else {
                        App.bubble(500, data["message"]);
                    }
                    //用户信息启用、停用后查询初始化
                    findUserInfoList(_path + "/user/list");
                },
                error: function () {
                    App.bubble(500, "启用、停用用户信息失败！");
                }
            });
        }

    }
}

//------详细信息修改-----
/**
 * @title : 以树的形式展示机构
 * */
function initOgrTree() {
    var url = _path + "/organ/organTree";
    $.ajax({
        type: "post",
        url: url,
        async: false,
        success: function (data) {
            var treeData = [];
            treeData.push({
                'id': '999999',
                'icon': '',
                'text': '机构列表',
                'isexpand': true,
                'pid': ""
            });
            var orgList = data.orgList;
            for (var i = 0; i < orgList.length; i++) {
                treeData.push({
                    'id': orgList[i].id,
                    'icon': '',
                    'text': orgList[i].organame,
                    'isexpand': true,
                    'pid': orgList[i].pid
                });
            }
            loadTree(treeData);
        }
    });
}

//加载树
function loadTree(dataTree) {
    var $$ = $("#orgTree");
    $$.html("<div style='height: 350px;overflow-y: auto'></div>");
    treeManger = $$.children().ligerTree({
        data: dataTree,
        idFieldName: 'id',
        parentIDFieldName: 'pid',
        checkbox: false,
        slide: true,
        nodeWidth: 120,
        onSelect: onSelect
    });
    var nodeId = $("#organid").val();
    if (nodeId != '-1' && nodeId != '') {
        var data = treeManger.getDataByID(nodeId);
        onclickPass(data);
        treeManger.selectNode(nodeId);
    }
}
function onSelect(note) {
    onclickPass(note.data);
}
function onclickPass(data) {
    var orgId = data.id;
    var organame = data.text;
    if (orgId == "-1") {
        $("#organid").val("999999");
        $("#organname").val("机构列表");
    } else {
        $("#organid").val(orgId);
        $("#organname").val(organame);
    }
}
